import { editInitList, initInstructAddressEdit, saveInstructAddressEdit } from "../../../../service/api/api-instruct-address";

interface TreeNode {
  id: string;
  name: string;
  parentId?: string;
  isChildren: number;
  checked: number;
  open: boolean;
  children?: TreeNode[];
}

Page({
  data: {
    tree: [] as TreeNode[],
    checkedKeys: [] as string[],
    loading: true,
    id: '', // 编辑的ID
    name: '',
    hasDataError: false, // 新增数据加载错误状态
    isEditMode: false, // 新增编辑模式标识
    editName: '',//编辑的联络人的名称
  },

  onLoad(options: { id?: string, name?: string }) {
    const isEditMode = !!options.id;
    if (options.id) {
      this.setData({
        isEditMode,
        id: options.id || '',
        editName: options.name ? decodeURIComponent(options.name) : ''
      });
      this.loadEditData(options.id);
    }
    this.loadTreeData();
  },

  // 加载编辑数据
  async loadEditData(id: string) {
    try {
      const response = await editInitList({ id });
      if (response.code === 0) {
        this.setData({
          name: this.data.editName,
          checkedKeys: response.data || []
        });
      }
    } catch (error) {
      console.error('加载编辑数据失败', error);
      this.setData({ hasDataError: true });
    }
  },

  // 加载树形数据 - 关键修改点
  async loadTreeData() {
    try {
      this.setData({
        loading: true,
        hasDataError: false
      });

      const response = await initInstructAddressEdit();

      if (response.code === 0) {
        const processedData = this.processTreeData(response.data);

        this.setData({
          tree: processedData,
          loading: false,
          // 确保数据更新后重新设置选中状态
          checkedKeys: this.data.checkedKeys
        });

        // 强制更新视图
        if (processedData.length === 0) {
          this.setData({ hasDataError: true });
        }
      } else {
        this.setData({
          loading: false,
          hasDataError: true
        });
      }
    } catch (error) {
      console.error('加载树形数据失败', error);
      this.setData({
        loading: false,
        hasDataError: true
      });
    }
  },

  // 处理树形数据
  processTreeData(data: any[]): TreeNode[] {
    if (!data || !Array.isArray(data)) return [];

    return data.map(item => ({
      id: item.id,
      name: item.name || '未命名节点',
      parentId: item.parentId,
      isChildren: item.children && item.children.length > 0 ? 1 : 0,
      checked: this.data.checkedKeys.includes(item.id) ? 1 : 0,
      open: false,
      children: item.children ? this.processTreeData(item.children) : undefined
    }));
  },

  // 树形选择变化
  onTreeChange(e: WechatMiniprogram.CustomEvent) {
    const { names, idList } = e.detail;
    console.log(names, idList);

    this.setData({
      checkedKeys: idList
    });
  },

  // 名称输入
  onNameInput(e: WechatMiniprogram.Input) {
    this.setData({
      name: e.detail.value
    });
  },

  // 保存数据
  async handleSave() {
    if (!this.data.name) {
      wx.showToast({ title: '请输入名称', icon: 'none' });
      return;
    }

    if (this.data.loading) {
      wx.showToast({ title: '数据正在加载，请稍候', icon: 'none' });
      return;
    }

    try {
      wx.showLoading({ title: '保存中...', mask: true });
      // 根据是否有ID决定保存参数
      const params = {
        name: this.data.name,
        combineIds: this.data.checkedKeys
      };

      // 只有编辑模式才传ID
      if (this.data.isEditMode) {
        (params as any).id = this.data.id;
      }
      const res = await saveInstructAddressEdit(params);

      wx.hideLoading();

      if (res.code === 0) {
        wx.showToast({ title: '保存成功' });

        // 返回前刷新上级页面数据
        const pages = getCurrentPages();
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2];
          if (prevPage.route === 'pages/instruct/purple/index') {
            prevPage.onShow(); // 触发上级页面刷新
          }
        }

        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({ title: res.message || '保存失败', icon: 'none' });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ title: '保存失败', icon: 'none' });
      console.error('保存失败', error);
    }
  }
});